import {
  createPopup,
  getPopupById,
  updatePopup,
  updatePopupPositition,
  closePopup,
} from "../popup/index";
import { LayerConfig, addLayer, LayerType ,removeLayer} from "../layer/layerManage.ts";
import { getLayerManagerState } from "../layer/layerManagerState.ts";

// 定义一个函数clusterLayer，用于生成一个包含设备信息的HTML字符串
function clusterLayer(options: any) {
  // 确保 options.data 是对象，如果是字符串则解析它
  if (typeof options.data === 'string') {
    try {
      options.data = JSON.parse(options.data);
    } catch (error) {
      console.error('解析 options.data 时出错:', error);
      options.data = {}; // 解析失败时提供一个空对象作为默认值
    }
  } else if (!options.data || typeof options.data !== 'object') {
    // 如果不是字符串也不是对象，提供默认空对象
    options.data = {};
  }
  // 返回一个包含设备信息的HTML字符串
  return `<div style="
        background: #FFFFFF;
        border-radius: 6px;
        padding: 8px;
        width: 200px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        font-family: Arial, sans-serif;
      ">
        <div style="
          display: flex;
          align-items: center;
          gap: 4px;
          padding-bottom: 6px;
          border-bottom: 1px solid #F0F0F0;
        ">
          <div style="
            background: #437EF1;
            color: white;
            padding: 2px 4px;
            border-radius: 4px;
            font-size: 9px;
          ">设备信息</div>
          <div style="
            color: #437EF1;
            font-size: 11px;
            font-weight: 500;
          ">${options.label || '永发乡红石村'}</div>
        </div>
        <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap:2px; text-align: center;">
          <div>
            <div style="color: #909399; font-size: 9px;">设备ID</div>
            <div style="color: #437EF1; font-size: 10px; line-height: 12px;font-weight: 500; font-family: DIN;">
              ${options.data.devId || '715'}
            </div>
          </div>
          <div>
            <div style="color: #909399; font-size: 9px;">设备类型</div>
            <div style="color: #437EF1; font-size: 10px;line-height: 12px; font-weight: 500; font-family: DIN;">
              ${options.data.devType || '火箭类'}
            </div>
          </div>
          <div>
            <div style="color: #909399; font-size: 9px;">设备名称</div>
            <div style="color: #437EF1; font-size: 10px;line-height: 12px; font-weight: 500; font-family: DIN;">
              ${options.data.devName || '火箭发射架'}
            </div>
          </div>
          <div>
            <div style="color: #909399; font-size: 9px;">设备型号</div>
            <div style="color: #437EF1; font-size: 10px;line-height: 12px; font-weight: 500; font-family: DIN;">
              ${options.data.devModel || 'WR-98'}
            </div>
          </div>
          <div>
            <div style="color: #909399; font-size: 9px;">设备状态</div>
            <div style="color: #437EF1; font-size: 10px;line-height: 12px; font-weight: 500; font-family: DIN;">
              ${options.data.devStatus || '在用'}
            </div>
          </div>
          <div>
            <div style="color: #909399; font-size: 9px;">检查状态</div>
            <div style="color: #437EF1; font-size: 10px;line-height: 12px; font-weight: 500; font-family: DIN;">
              ${options.data.devCheckStatus || '合格'}
            </div>
          </div>
          <div>
            <div style="color: #909399; font-size: 9px;">经度</div>
            <div style="color: #437EF1; font-size: 10px;line-height: 12px; font-weight: 500; font-family: DIN;">
              ${Number(options.data.pointLongi).toFixed(6) || '124.93611111111112'}
            </div>
          </div>
          <div>
            <div style="color: #909399; font-size: 9px;">纬度</div>
            <div style="color: #437EF1; font-size: 10px;line-height: 12px; font-weight: 500; font-family: DIN;">
              ${Number(options.data.pointLati).toFixed(6) || '43.77916666666667'}
            </div>
          </div>
        </div>
      </div>`;
}

/**
 * 加载聚合源
 * @param map - 地图实例
 * @param sourceName - 源名称
 * @param data - 地理JSON数据
 */
export const loadClusterSource = (map: any, sourceName: string, data: any) => {
  try {
    // 检查源是否已存在，避免重复添加
    // if (!map.getSource(`${sourceName}_source`)) {
      const source = {
        type: "geojson",
        data,
        cluster: true,
        clusterRadius: 30,
        clusterMaxZoom: 14, // 在第14级缩放时显示单个标记
      };
      // map.addSource(`${sourceName}_source`, source);
      // 加载聚合图层
      loadClusterLayer(map, `${sourceName}_layer`, source);
    // }
  } catch (error) {
    console.error(`加载聚合源 ${sourceName} 时出错:`, error);
  }
};

/**
 * 加载聚合图层
 * @param map - 地图实例
 * @param layerName - 图层名称
 * @param source - 源对象
 */
export const loadClusterLayer = (map: any, layerName: string, source: any) => {
  try {
    // 检查图层是否已存在，避免重复添加
    if (!map.getLayer(layerName)) {
      // 添加实际的点（显示真实标记和图片）
      const layerActual: LayerConfig = {
        id: `${layerName}_point`,
        type: LayerType.Symbol,
        source: source,
        filter: ["!has", "point_count"], // 过滤聚合点，显示真实的标记
        layout: {
          "icon-image": ["get", "imageName"], // 使用自定义图标
          "icon-size": 0.19, // 调整图标大小
          "text-field": "{label}", // 显示名称或其他字段
          "text-font": ["MicrosoftYaHei"],
          "text-size": 10, // 调整字体大小
          "text-offset": [0.5, 2.5], // 调整文字偏移
        },
      };
      addLayer(getLayerManagerState(map), layerActual);

      // 添加聚合层
      const layerCluster: LayerConfig = {
        id: layerName,
        type: LayerType.Symbol,
        source: source,
        layout: {
          "icon-size": ["case", ["has", "point_count"], 0.2, 0.1], // 调整聚合点图标大小
          "icon-image": [
            "case",
            ["has", "point_count"], // 条件1
            "position", // 结果1
            ["get", "defaultIcon"],
          ], // 聚合点图标
          "text-field": ["get", "point_count_abbreviated"], // 聚合点数量
          "text-font": ["MicrosoftYaHei"], // 聚合点字体
          "text-offset": [0.5, -0.05], // 调整聚合点数量偏移
          "text-size": 18, // 调整聚合点数量大小
          "icon-ignore-placement": true, // 聚合点图标忽略覆盖
        },
        paint: {
          "text-color": "#FFFFFF", // 文字颜色
          // "text-halo-width": 1, // 背景宽度
          // "text-halo-color": "rgba(0, 0, 0, 0.8)", // 背景颜色
          // "text-halo-blur": 0.5, // 背景模糊
        },
      };
      addLayer(getLayerManagerState(map), layerCluster);
    }
  } catch (error) {
    console.error(`加载聚合图层 ${layerName} 时出错:`, error);
  }
};

/**
 * 删除聚合图层
 * @param map - 地图实例
 * @param layerName - 图层名称
 */
export const removeClusterLayer = (map: any, layerName: string) => {
  try {
    if (map.getLayer(`${layerName}`)) {
      removeLayer(getLayerManagerState(map), `${layerName}`);
    }
    if (map.getLayer(`${layerName}_point`)) {
      removeLayer(getLayerManagerState(map), `${layerName}_point`);
    }
    // 删除Popup
    closePopup("cluster_popup");
  } catch (error) {
    console.error(`删除聚合图层 ${layerName} 时出错:`, error);
  }
};

/**
 * 处理点击事件
 * @param map - 地图实例
 * @param layerId - 图层ID
 */
const handleClick = (map: any, layerId: string) => {
  if (!map.__clickHandlerAdded) {
    map.on("click", (e: any) => {
      const features = map.queryRenderedFeatures(e.point);
      if (features.length === 0) {
        closePopup("cluster_popup");
      }
    });
    map.__clickHandlerAdded = true;
  }

  map.on("click", layerId, (e: any) => {
    try {
      const features = map.queryRenderedFeatures(e.point, { layers: [layerId] });

      if (features.length > 0) {
        const properties = features[0].properties;
        const coordinates = features[0].geometry.coordinates;
        
        if (!properties || !properties.data) {
          closePopup("cluster_popup");
          return;
        }
        
        let popup = getPopupById("cluster_popup");
        if (!popup) {
          popup = createPopup(
            map,
            "cluster_popup",
            coordinates,
            clusterLayer(properties)
          );
        } else {
          updatePopupPositition("cluster_popup", coordinates);
          updatePopup(
            popup,
            clusterLayer(properties)
          );
        }
      } else {
        closePopup("cluster_popup");
      }
    } catch (error) {
      console.error("处理点击事件时出错:", error);
      closePopup("cluster_popup");
    }
  });
};

/**
 * 处理聚合开关
 * @param map - 地图实例
 * @param sourceName - 源名称
 * @param data - 地理JSON数据
 * @param isCluster - 是否开启聚合
 */
export const toggleCluster = (map: any, sourceName: string, data: any, isCluster: boolean) => {
  // 先关闭所有可能存在的弹窗
  closePopup("cluster_popup");
  
  // 移除之前的所有点击事件监听器
  map.off("click", `${sourceName}_layer`);
  map.off("click", `${sourceName}_layer_point`);
  map.off("click", `${sourceName}_non_cluster_layer`);

  if (isCluster) {
      // 开启聚合
      const clusterSource = {
          type: "geojson",
          data,
          cluster: true,
          clusterRadius: 30,
          clusterMaxZoom: 14
      };
      loadClusterLayer(map, `${sourceName}_layer`, clusterSource);

      // 绑定聚合点点击事件
      handleClick(map, `${sourceName}_layer`);
      handleClick(map, `${sourceName}_layer_point`);

      // 移除非聚合图层和源
      if (map.getLayer(`${sourceName}_non_cluster_layer`)) {
          removeLayer(getLayerManagerState(map), `${sourceName}_non_cluster_layer`);
      }
 
  } else {
      // 关闭聚合
      // 移除聚合图层和源
      removeClusterLayer(map, `${sourceName}_layer`);

      // 添加非聚合源
      const nonClusterSource = {
          type: "geojson",
          data
      };
      // 添加非聚合图层
      if (!map.getLayer(`${sourceName}_non_cluster_layer`)) {
          const layerConfig: LayerConfig = {
              id: `${sourceName}_non_cluster_layer`,
              type: LayerType.Symbol,
              source: nonClusterSource,
              layout: {
                  "icon-image": ["get", "imageName"],
                  "icon-size": 0.19,
                  "text-field": "{label}",
                  "text-font": ["MicrosoftYaHei"],
                  "text-size": 10,
                  "text-offset": [0.5, 2.5]
              },
              // 确保过滤条件正确，不显示聚合点
              filter: ["!has", "point_count"] 
          };
          addLayer(getLayerManagerState(map), layerConfig);
      }

      // 绑定实际点点击事件
      handleClick(map, `${sourceName}_non_cluster_layer`);
  }
};

/**
 * 释放资源
 * @param map - 地图实例
 * @param sourceName - 源名称
 */
export const releaseResources = (map: any, sourceName: string) => {
  // 移除聚合相关图层
  if (map.getLayer(`${sourceName}_layer`)) {
    removeLayer(getLayerManagerState(map), `${sourceName}_layer`);
  }
  if (map.getLayer(`${sourceName}_layer_point`)) {
    removeLayer(getLayerManagerState(map), `${sourceName}_layer_point`);
  }



  // 移除实际点相关图层
  if (map.getLayer(`${sourceName}_non_cluster_layer`)) {
    removeLayer(getLayerManagerState(map), `${sourceName}_non_cluster_layer`);
  }
  // 移除所有点击事件监听器
  map.off("click", `${sourceName}_layer`);
  map.off("click", `${sourceName}_layer_point`);
  map.off("click", `${sourceName}_non_cluster_layer`);

  // 关闭Popup
  closePopup("cluster_popup");
};

/**
 * 修改实际点的属性
 * @param map - 地图实例
 * @param sourceName - 源名称
 * @param properties - 要修改的属性对象，例如 { "icon-size": 0.2, "text-size": 12 }
 */
export const updateActualPointsProperties = (map: any, sourceName: string, properties: any) => {
  const layerId = `${sourceName}_non_cluster_layer`;
  if (map.getLayer(layerId)) {
    map.setLayoutProperty(layerId, "icon-size", properties["icon-size"]);
    // 这里可以扩展更多属性的修改，例如 text-size, text-offset 等
    if (properties["text-size"]) {
      map.setLayoutProperty(layerId, "text-size", properties["text-size"]);
    }
    if (properties["text-offset"]) {
      map.setLayoutProperty(layerId, "text-offset", properties["text-offset"]);
    }
    // 以此类推，根据实际需求添加更多属性的修改逻辑
  }
};

/**
 * 关闭聚合点弹窗
 * @description 可以从外部调用此方法来关闭弹窗
 */
export const closeClusterPopup = (): void => {
  closePopup("cluster_popup");
};